var logger = require('koa-logger');
var session = require('koa-generic-session');
var redisStore = require('koa-redis');
var serve = require('koa-static')
var koa = require('koa')
var app = koa();

var config = require('./config')
var utils = require('./common/utils')

// middleware
app.use(logger());

app.keys = ['iwfe'];
app.use(session({
    key: 'iwfe',
    prefix: 'user-',
    rolling: true,
    cookie: {
        path: '/',
        httpOnly: true,
        maxage: 1000 * 60 * 60 * 24 * 7,
        rewrite: true,
        signed: false
    },
    store: redisStore(config.redis)
}));


app.use(function*(next) {
    this.locals = {}

    this.set({
        'Pragma': 'No-cache',
        'Cache-Control': 'no-cache'
    })

    var user = this.session.user || null

    if (user) {
        this.locals._user = utils.wrapUser(utils.extend({}, user));
    }

    this.locals._now = new Date().getTime()

    yield next;
});

var main = require('./router/main');
var blog = require('./router/blog');
var collects = require('./router/collects');
var user = require('./router/user');
var api = require('./router/api');

app.use(main.routes());
app.use(blog.routes());
app.use(collects.routes());
app.use(user.routes());
app.use(api.routes());

if (config.env == 'dev') {
    app.use(serve(__dirname));
}

app.use(function*(next) {

});

app.on('error', function(err) {
    console.log('sent error %s to the cloud', err.message);
    console.log(err);
});

module.exports = app;
